package com.ytktt.study.week7.task9.aspect;

import com.ytktt.study.week7.task9.annotation.TargetDataSource;
import com.ytktt.study.week7.task9.constant.DataSourceConstant;
import com.ytktt.study.week7.task9.ds.context.DynamicDataSourceContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 动态数据源切换切面
 *
 * @author ytk
 */
@Order(1)
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.ytktt.study.week7.task9.annotation.TargetDataSource)")
    public void pointCut() {}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        TargetDataSource targetDataSource = null;
        if (pjp.getSignature() instanceof MethodSignature) {
            Method method = ((MethodSignature) pjp.getSignature()).getMethod();
            if (method != null) {
                targetDataSource = method.getAnnotation(TargetDataSource.class);
            }
        }
        if (targetDataSource == null) {
            DynamicDataSourceContext.setDataSourceRoutingKey(DataSourceConstant.WRITE_KEY);
        } else {
            DynamicDataSourceContext.setDataSourceRoutingKey(targetDataSource.value());
        }
        log.info("target datasource: {}", DynamicDataSourceContext.getDataSourceRoutingKey());

        try {
            return pjp.proceed();
        } finally {
            DynamicDataSourceContext.clearRoutingThreadLocal();
        }
    }
}
